// Pryn editor program.
#include <pryn.h>
#include <prynEditor.h>
#include <windows.h>

PrynResult print (PrynState *state, const PrynString *text)
{
	try
	{
	#if _WIN32
	#if 1
		const char *z = text->toZ (state);
		OutputDebugString (z);
		text->freeZ (state, z);
	#else
		HANDLE handle = GetStdHandle (STD_OUTPUT_HANDLE);
		DWORD written;
		
		if (handle) WriteFile (handle, text->pointer, text->length, &written, 0);
	#endif
	#endif
	}
	catch (PrynException &exception)
	{
		return exception.result;
	}

	return PrynResultSuccess;
}

void run ()
{
	PrynState *state;

	PrynEditorBoard *board;
	PrynString string, name, description;
	
	state = PrynState::Create ();
	//state->addLibraryPath ("Libraries");
	state->printFunction (&print);
	//state->loadLibraries ("Libraries");
	state->loadAndSaveCache ();
	/*if ((result = prynStateCreate (&state)) < 0)
	{
		prynStringLiteral (&string, "Pryn state allocation failed.\n");
		print (0, &string);
		return -1;
	}*/
	
	state->print ("Mediators:\n");
	for (PrynMediator *mediator = 0; state->iterateMediators (&mediator); )
	{
		state->print ("\t%r: %r\n", mediator->name (), mediator->description ());
		mediator->enable ();
	}
	
	state->print ("Libraries:\n");
	for (PrynLibrary *library = 0; state->iterateLibraries (&library); )
		state->print ("\t%r: %r\n", library->name (), library->description ());
		
	state->print ("Types:\n");
	for (PrynType *type = 0; state->iterateTypes (&type); )
		state->print ("\t%r: %r\n", type->name (), type->description ());
	
	state->print ("Factories:\n");
	for (PrynFactory *factory = 0; state->iterateFactories (&factory); )
		state->print ("\t%r: %r\n", factory->name (), factory->description ());

	board = PrynEditorBoard::Create (state, "Pryn Graph Editor");	
	prynGuiMessageLoop (state);
	
	state->print ("Terminated successfully!\n");
}

#if _WIN32
int __stdcall WinMain (HINSTANCE instance, HINSTANCE previousInstance, LPSTR commandLine, int showCommand)
#else
int main ()
#endif
{
	try
	{
		run ();
	}
	catch (PrynException &exception)
	{
		prynGuiReportError (exception.state, exception.result);
	}

#if _WIN32
	ExitProcess (0);
#endif
	return 0;
}